#!/usr/bin/env python
# coding: utf-8

"""
make 09light beep file from .wav files
native endian
edit the following config variable:
	BEEP_FILE_CONTENT
	WAVE_DATA_PATH
	OUTPUT_FILE_NAME
"""

#################################################
# edit the config variable BEEP_FILE_CONTENT
BEEP_FILE_CONTENT = {
	'Volume Label': 'OPERATION SOUND',		# 16*char
	'Date': '200812151003',							# 12*char
	'Version': '0.02',						# 4*char
	'WaveData': [						# ID: DWORD, Offset: DWORD, DataSize: DWORD
		# (ID, FileName),
		#(0, 'PSG2Hi.wav'),
		#(1, 'PSG2LOW.wav'),
		(12, '00.wav'),
		(13, '01.wav'),
		(14, '02.wav'),
		(15, '03.wav'),
		(16, '04.wav'),
		(17, '05.wav'),
		(18, '06.wav'),
		(19, '07.wav'),
	]
}

def n2s(n):
	s = str(n)
	if len(s) == 1:
		s = '0' + s
	return s

for n in range(39, 67):
	BEEP_FILE_CONTENT['WaveData'].append((n, n2s(n-31)+'.wav'))

print BEEP_FILE_CONTENT['WaveData']

# path where stores the .wav file, default is '.'
WAVE_DATA_PATH = r'.'

# output file name
OUTPUT_FILE_NAME = r"BEEPS.09LIGHT"
##################################################



import os,sys
import array
import ConfigParser



def CreateBeepFile(ofn):
	BEEP_FILE_CONTENT['WaveData'].sort(key = lambda x:x[0])
	of = open(ofn, 'wb')
	bfc = BEEP_FILE_CONTENT
	vl = (bfc['Volume Label'] + '\0'*16)[:16]
	d = (bfc['Date'] + '\0'*12)[:12]
	ver = (bfc['Version']+ '\0'*4)[:4]
	log(of.tell(), 'Volume Label', vl)
	of.write(vl)
	log(of.tell(), 'Date', d)
	of.write(d)
	log(of.tell(), 'Version', ver)
	of.write(ver)
	num = len(bfc['WaveData'])
	print 'Count: %d' % (num)
	of.write(array.array('I', (num,)).tostring())

	fheadLen = 16+12+4+4+len(bfc['WaveData'])*(4+4+4)
	wd = bfc['WaveData']
	for n in range(len(wd)):
		w = wd[n]
		id = w[0]
		ofs = fheadLen + sum((os.path.getsize(f) for f in \
					(WAVE_DATA_PATH + '\\'+wfn[1] for wfn in wd[:n])))
		dsize = os.path.getsize(WAVE_DATA_PATH + '\\' + wd[n][1])
		log(of.tell(), 'id, offset, dsize', str(id)+' '+str(ofs)+' '+str(dsize))
		of.write(array.array('I', [id, ofs, dsize]).tostring())
	for w in wd:
		log(of.tell(), 'wav data', str(w[0]) + ' ' + w[1])
		of.write(open(WAVE_DATA_PATH+'\\'+w[1], 'rb').read())
	of.close()


def log(ofs, vname, val=''):
	print 'write %s at offset %d \n %s = %s'%(vname, ofs, vname, val)

def __main__():
	CreateBeepFile(OUTPUT_FILE_NAME)


if __name__=='__main__':
	__main__()



